package ext.opensource.netty.server.httpsocket;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.ssl.SslHandler;

public class WebSocketUtil {
	public static ChannelFuture sendTextMessage(final ChannelHandlerContext ctx, final String msg) {
		return ctx.writeAndFlush(new TextWebSocketFrame(msg));
	}

	public static ChannelFuture sendBinnaryMessage(final ChannelHandlerContext ctx, final ByteBuf msg) {
		return ctx.writeAndFlush(new BinaryWebSocketFrame(msg));
	}

	public static String getWebSocketLocation(final ChannelPipeline cp, final HttpRequest req, final String path) {
		return WebSocketUtil.getWebSocketLocation(cp.get(SslHandler.class) != null, req, path);
	}

	public static String getWebSocketLocation(final boolean bSSL, final HttpRequest req, final String path) {
		String protocol = "ws";
		if (bSSL) {
			protocol = "wss";
		}
		return protocol + "://" + req.headers().get(HttpHeaderNames.HOST) + path;
	}
}
